const express = require('express')
const cors = require('cors')
const path = require('path')
const jwt = require('express-jwt')
const loginRouter = require(path.join(__dirname, 'routers', 'login.js'))
const myRouter = require(path.join(__dirname, 'routers', 'my.js'))
const cateRouter = require(path.join(__dirname, 'routers', 'cate.js'))
const articleRouter = require(path.join(__dirname, 'routers', 'article.js'))
const db = require(path.join(__dirname, 'common', 'db.js'))
const app = express()

// 处理客户端请求post参数
// for parsing application/json
app.use(express.json()) 
// for parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true })) 

// 配置后端的cors跨域
app.use(cors())

// 把uploads目录编程静态资源目录
app.use('/uploads', express.static('uploads'))

// 配置jwt的token解析中间件
// unless作用：排除一些路径，不用解析token
app.use(jwt({
  secret: 'bigevent'
}).unless({path: /^\/api/}))

// 配置路由模块
app.use('/api', loginRouter)
app.use('/my', myRouter)
app.use('/my', cateRouter)
app.use('/my', articleRouter)

app.get('/data', async (req, res) => {
  let sql = 'select * from user'
  // db.operateData(sql, null).then((result) => {
  //   res.send(result)
  // })
  let result = await db.operateData(sql)
  res.send(result)
})

app.listen(8888, () => {
  console.log('running...')
})